package com.exam.servlet;

import com.alibaba.fastjson2.JSON;
import com.exam.domain.entity.*;
import com.exam.service.ExamService;
import com.exam.service.QuestionService;
import com.exam.service.RecordService;
import com.exam.service.TeacherService;
import com.exam.service.impl.ExamServiceImpl;
import com.exam.service.impl.QuestionServiceImpl;
import com.exam.service.impl.RecordServiceImpl;
import com.exam.service.impl.TeacherServiceImpl;
import com.exam.util.BaseResult;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;

@WebServlet(urlPatterns = "/teacher/*",asyncSupported = true)
public class TeacherServlet extends HttpServlet {

    private TeacherService teacherService;
    private QuestionService questionService;
    private ExamService examService;
    private RecordService recordService;

    @Override
    public void init() throws ServletException {
        super.init();
        teacherService = new TeacherServiceImpl();
        questionService = new QuestionServiceImpl();
        examService = new ExamServiceImpl();
        recordService = new RecordServiceImpl();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String path = req.getRequestURI(); // 获取请求的URI
        if (path.endsWith("/home")) {
            // 页面逻辑处理，返回 home.jsp 视图
            System.out.println("转发到教师端页面");
            RequestDispatcher dispatcher = req.getRequestDispatcher("/WEB-INF/pages/teacher/home.jsp");
            dispatcher.forward(req, resp);  // 转发到 home.jsp
//            resp.sendRedirect("/WEB-INF/pages/home.jsp");
        } else if (path.endsWith("/examManage")) {
            RequestDispatcher dispatcher = req.getRequestDispatcher("/WEB-INF/pages/teacher/examManage.jsp");
            dispatcher.forward(req, resp);
        } else if (path.endsWith("/questionBank")){
            RequestDispatcher dispatcher = req.getRequestDispatcher("/WEB-INF/pages/teacher/questionBank.jsp");
            dispatcher.forward(req, resp);
        }else if (path.endsWith("/studentScores")){
            RequestDispatcher dispatcher = req.getRequestDispatcher("/WEB-INF/pages/teacher/studentScores.jsp");
            dispatcher.forward(req, resp);
        }else if (path.endsWith("/getAllQuestions")){
            //开启异步请求
            req.startAsync();

            User user = (User)req.getSession().getAttribute("user");
            Integer teacherId = user.getUserId();
            BaseResult<List<Question>> result = teacherService.getAllQuestionsByTeacherId(teacherId);

            // 设置响应的内容类型为 JSON
            resp.setContentType("application/json;charset=UTF-8");

            // 使用 Fastjson 将 BaseResult 对象转换为 JSON 并写入响应
            String jsonResponse = JSON.toJSONString(result);
            resp.getWriter().write(jsonResponse);
            //关闭异步请求
            req.getAsyncContext().complete();
        }else if (path.endsWith("/getExams")){
            //开启异步请求
            req.startAsync();
            User user = (User)req.getSession().getAttribute("user");
            Integer teacherId = user.getUserId();
            BaseResult<List<Exam>> result = teacherService.getExams(teacherId);
            // 设置响应的内容类型为 JSON
            resp.setContentType("application/json;charset=UTF-8");

            // 使用 Fastjson 将 BaseResult 对象转换为 JSON 并写入响应
            String jsonResponse = JSON.toJSONString(result);
            resp.getWriter().write(jsonResponse);
            //关闭异步请求
            req.getAsyncContext().complete();
        }else if(path.endsWith("/getQuestionDetails")){
            //开启异步请求
            req.startAsync();
            Integer questionId = Integer.parseInt(req.getParameter("id"));

            BaseResult<Question> result = questionService.getQuestionDetailsById(questionId);
            // 设置响应的内容类型为 JSON
            resp.setContentType("application/json;charset=UTF-8");

            // 使用 Fastjson 将 BaseResult 对象转换为 JSON 并写入响应
            String jsonResponse = JSON.toJSONString(result);
            resp.getWriter().write(jsonResponse);
            //关闭异步请求
            req.getAsyncContext().complete();
        }else if(path.endsWith("/searchQuestions")){
            //开启异步请求
            req.startAsync();
            User user = (User)req.getSession().getAttribute("user");
            Integer teacherId = user.getUserId();

            String questionText = '%'+req.getParameter("keyword")+'%';

            BaseResult<List<Question>> result = teacherService.getQuestionsByQuestionText(teacherId,questionText);

            // 设置响应的内容类型为 JSON
            resp.setContentType("application/json;charset=UTF-8");

            // 使用 Fastjson 将 BaseResult 对象转换为 JSON 并写入响应
            String jsonResponse = JSON.toJSONString(result);
            resp.getWriter().write(jsonResponse);
            //关闭异步请求
            req.getAsyncContext().complete();
        }else if(path.contains("/getExamDetails")){
            //开启异步请求
            req.startAsync();
            // 获取？id=xxx的参数，试卷id
            Integer examId = Integer.parseInt(req.getParameter("id"));
            // 查询试卷详情信息
            BaseResult<Exam> result =  examService.findExamItemsByExamId(examId);

            // 设置响应的内容类型为 JSON
            resp.setContentType("application/json;charset=UTF-8");

            // 使用 Fastjson 将 BaseResult 对象转换为 JSON 并写入响应
            String jsonResponse = JSON.toJSONString(result);
            resp.getWriter().write(jsonResponse);
            //关闭异步请求
            req.getAsyncContext().complete();
        }else if(path.endsWith("/getTeacherInfo")){
            //开启异步请求
            req.startAsync();
            User user = (User)req.getSession().getAttribute("user");
            Integer teacherId = user.getUserId();
            BaseResult<Teacher> result = teacherService.getTeacherInfo(teacherId);

            // 设置响应的内容类型为 JSON
            resp.setContentType("application/json;charset=UTF-8");

            // 使用 Fastjson 将 BaseResult 对象转换为 JSON 并写入响应
            String jsonResponse = JSON.toJSONString(result);
            resp.getWriter().write(jsonResponse);
            //关闭异步请求
            req.getAsyncContext().complete();
        }else if(path.endsWith("/getStudentScores")){
            //开启异步请求
            req.startAsync();
            User user = (User)req.getSession().getAttribute("user");
            Integer teacherId = user.getUserId();
            // 获取？id=xxx的参数，试卷id
            Integer examId = Integer.parseInt(req.getParameter("id"));
            // 通过试卷ID，查询学生的考试记录
            BaseResult<List<Record>> result = teacherService.getStudentsExamRecord(examId);
            // 设置响应的内容类型为 JSON
            resp.setContentType("application/json;charset=UTF-8");

            // 使用 Fastjson 将 BaseResult 对象转换为 JSON 并写入响应
            String jsonResponse = JSON.toJSONString(result);
            resp.getWriter().write(jsonResponse);
            //关闭异步请求
            req.getAsyncContext().complete();
        }else if(path.endsWith("/getExamSolution")){
            // 查询试题解析
            req.startAsync();
            // 获取考试记录ID
            Integer recordId = Integer.parseInt(req.getParameter("recordId"));

            // 获得学生的考试记录，列表
            BaseResult<Record> result = recordService.getExamRecordItemsById(recordId);

            // 设置响应的内容类型为 JSON
            resp.setContentType("application/json;charset=UTF-8");

            // 使用 Fastjson 将 BaseResult 对象转换为 JSON 并写入响应
            String jsonResponse = JSON.toJSONString(result);
            resp.getWriter().write(jsonResponse);
            req.getAsyncContext().complete();
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String path = req.getRequestURI(); // 获取请求的URI
        System.out.println("进入post请求。。。");
        if (path.endsWith("/addQuestion")) {
            //开启异步请求
            req.startAsync();
            // 获取前端传递的参数
            String title = req.getParameter("title");
            String answer = req.getParameter("answer");
            String optionA = req.getParameter("optionA");
            String optionB = req.getParameter("optionB");
            String optionC = req.getParameter("optionC");
            String optionD = req.getParameter("optionD");
            // 添加人
            User user = (User)req.getSession().getAttribute("user");
            Integer teacherId = user.getUserId();
            BaseResult<String> result = teacherService.addQuestion(teacherId,title,answer,optionA,optionB,optionC,optionD);
            // 设置响应的内容类型为 JSON
            resp.setContentType("application/json;charset=UTF-8");

            // 使用 Fastjson 将 BaseResult 对象转换为 JSON 并写入响应
            String jsonResponse = JSON.toJSONString(result);
            resp.getWriter().write(jsonResponse);
            //关闭异步请求
            req.getAsyncContext().complete();
        }else if(path.endsWith("/createExam")){
            //开启异步请求
            req.startAsync();
            User user = (User)req.getSession().getAttribute("user");
            Integer teacherId = user.getUserId();

            // 获取请求参数
            String examTitle = req.getParameter("examTitle");

            int questionCount = Integer.parseInt(req.getParameter("questionCount"));
            int questionValue = Integer.parseInt(req.getParameter("questionValue"));

            BaseResult<String> result = teacherService.createExam(teacherId,examTitle,questionCount,questionValue);

            // 设置响应的内容类型为 JSON
            resp.setContentType("application/json;charset=UTF-8");

            // 使用 Fastjson 将 BaseResult 对象转换为 JSON 并写入响应
            String jsonResponse = JSON.toJSONString(result);
            resp.getWriter().write(jsonResponse);
            //关闭异步请求
            req.getAsyncContext().complete();
        }
    }

    @Override
    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("进入put请求。。。");
        String path = req.getRequestURI();
        // 更新试题
        if (path.endsWith("/updateQuestion")) {
//            req.startAsync();
            // 获取前端传递的参数
            // 读取请求体
            req.setCharacterEncoding("UTF-8"); // 设置请求编码
            StringBuilder jsonBuilder = new StringBuilder();
            try (BufferedReader reader = req.getReader()) {
                String line;
                while ((line = reader.readLine()) != null) {
                    jsonBuilder.append(line);
                }
            }
            // 将 JSON 数据解析为 Java 对象
            String json = jsonBuilder.toString();
            Question question = JSON.parseObject(json, Question.class);

            Integer questionId = question.getQuestionId();
            String questionText = question.getQuestionText();
            String correctOption = question.getCorrectOption();
            String optionA = question.getOptionA();
            String optionB = question.getOptionB();
            String optionC = question.getOptionC();
            String optionD = question.getOptionD();
            System.out.println(question);
            BaseResult<String> result = questionService.updateQuestion(questionId,questionText,correctOption,optionA,optionB,optionC,optionD);
            // 设置响应的内容类型为 JSON
            resp.setContentType("application/json;charset=UTF-8");

            // 使用 Fastjson 将 BaseResult 对象转换为 JSON 并写入响应
            String jsonResponse = JSON.toJSONString(result);
            resp.getWriter().write(jsonResponse);
            //关闭异步请求
//            req.getAsyncContext().complete();
        } else if (path.contains("/startExam")) {
            // 获取 URL 查询字符串中的参数
            Integer examId = Integer.parseInt(req.getParameter("id"));
//            System.out.println(examId);
            BaseResult<String> result = examService.activeExamStatus(examId);
//            BaseResult<String> result = BaseResult.success("ok");
            // 设置响应的内容类型为 JSON
            resp.setContentType("application/json;charset=UTF-8");

            // 使用 Fastjson 将 BaseResult 对象转换为 JSON 并写入响应
            String jsonResponse = JSON.toJSONString(result);
            resp.getWriter().write(jsonResponse);
        }else if (path.contains("/stopExam")) {
            // 获取 URL 查询字符串中的参数
            Integer examId = Integer.parseInt( req.getParameter("id"));
//            System.out.println(examId);
            BaseResult<String> result = examService.inactiveExamStatus(examId);
//            BaseResult<String> result = BaseResult.success("ok");
            // 设置响应的内容类型为 JSON
            resp.setContentType("application/json;charset=UTF-8");

            // 使用 Fastjson 将 BaseResult 对象转换为 JSON 并写入响应
            String jsonResponse = JSON.toJSONString(result);
            resp.getWriter().write(jsonResponse);
        }
    }

    @Override
    protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("进入delete请求。。。");
        String path = req.getRequestURI();
        // 更新试题
        if (path.contains("/deleteQuestion/")) {
            //开启异步请求
            req.startAsync();

            // 假设路径是 /teacher/deleteQuestion/{id}
            String[] pathParts = path.split("/");
            String questionIdStr = pathParts[pathParts.length - 1];  // 获取路径中的最后一个部分作为 ID
            Integer questionId = Integer.parseInt(questionIdStr);
//            System.out.println(questionId);
            BaseResult<String> result = questionService.deleteQuestionById(questionId);

            // 设置响应的内容类型为 JSON
            resp.setContentType("application/json;charset=UTF-8");

            // 使用 Fastjson 将 BaseResult 对象转换为 JSON 并写入响应
            String jsonResponse = JSON.toJSONString(result);
            resp.getWriter().write(jsonResponse);
            req.getAsyncContext().complete();
        }
    }
}
